﻿using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Models.Common;
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using UtilsORM;
using UtilsORM.MySqlData;

////using System.Web.Script.Serialization;

namespace GatewayServerService.Data
{
    public class DBIotDeviceModel
    {
        EFYihongIotContext ef = new EFYihongIotContext();
        public List<iot_device_model> getModelList()
        {
            return ef.iot_device_model.Where(c => c.m_status == 0).ToList();
        }
        public iot_device_model getModel(string mguid)
        {
            return ef.iot_device_model.Where(c => c.m_guid == mguid).FirstOrDefault();
        }
        public bool saveAll(IFormCollection FC, HttpReqModel httpRequest, MagerLoginInfo LoginUserInfo, iot_device_model req)
        {
            //先查一下有没重复提交
            iot_device_model model = ef.iot_device_model.Where(c => c.m_guid == req.m_guid).FirstOrDefault();
            if (model == null)
            {
                //查编码
                iot_device_model getcode = ef.iot_device_model.OrderByDescending(c => c.m_id).FirstOrDefault();
                if (getcode != null)
                {
                    req.m_code = (int.Parse(getcode.m_code) + 1).ToString();
                }
                else
                {
                    req.m_code = "1001";
                }
                //写入
                req.m_add_time = DateTime.Now;
                req.m_c_guid = LoginUserInfo.userCompanyGuid;
                //if(req.m_agreement_guid!=null)
                //{
                //    req.m_agreementType = ef.iot_device_agreement.Where(c => c.a_guid == req.m_agreement_guid).FirstOrDefault().a_name;
                //}
                ef.iot_device_model.Add(req);
                ef.SaveChanges();
            }
            else
            {
                model.m_name = req.m_name;
                model.m_type_guid = req.m_type_guid;
                model.m_remark = req.m_remark;
                model.m_parameter_demo = req.m_parameter_demo;
                //model.m_agreement_guid = req.m_agreement_guid;
                model.m_status = req.m_status;
                //if (req.m_agreement_guid != null)
                //{
                //    req.m_agreementType = ef.iot_device_agreement.Where(c => c.a_guid == req.m_agreement_guid).FirstOrDefault().a_name;
                //}
                ef.iot_device_model.Update(model);
                ef.SaveChanges();
            }
            return true;
        }

    }
}
